"""
输入网易云歌手id即可下载该歌手TOP50歌曲
"""
import requests
import execjs
import json
import re
import os


headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0',
    'cookie': 'NMTID=00OxfTjjDy90EOU1k_jg8NKv6tVBH4AAAGLR481NQ; _ntes_nnid=f5aa7c67048ec27947eab44cd693c52b,1697712650903; _ntes_nuid=f5aa7c67048ec27947eab44cd693c52b; WM_TID=qwlz%2BvANB9RBRAUVFRfU2jFqwe9aP41q; WEVNSM=1.0.0; WNMCID=vgxtxo.1697712652548.01.0; ntes_utid=tid._.KDgXpVIRzyNAVhBQFAPQn3UuhP5wQKiH._.0; sDeviceId=YD-5%2B537F6mJy9AFxAAQUaAi1sDKIrneLk6; __snaker__id=vUotyW5YJOUlrIKG; YD00000558929251%3AWM_NI=gFnc25gnMZEG8%2BF0uFxUcpFhSCJKnJcKiCHouWhKZAxAKsIOt51CIhOQuENH8768FKnz%2FiOD5WGZILwbZTBKzxbPznPtvVoGVai0NXcts9dUvzfK%2FGLnTMyyYeP1HEEubW8%3D; YD00000558929251%3AWM_NIKE=9ca17ae2e6ffcda170e2e6eeb9ef7f968eaab9fc4ea9a88ea7c14e839a8aadc439f28abf98fb54b899f7b0c12af0fea7c3b92aa59aa284b13fa5b283bbc84dfcf58ad1f84ebc8bad91c564919d86aced42a195a7a4cb65b789a8acd94bbc9f8594cc45b8ebffa4cc648d8fbba6cd44fce9fad9c541aea6e18ace50f78989bbcc48b5be96b5c141baa8aeb1f96694acbab7ee4d96bfa7d1cd54a1acbddae75fb6a6aaacae4d90b29caefc739bbba0d2cb4f87abaeb8bb37e2a3; YD00000558929251%3AWM_TID=4fZ72Z5HqTdEUFVRREaQmyFqllStCtPE; ntes_kaola_ad=1; __remember_me=true; MUSIC_U=00254EB867211DFF94D4807546B693089FC4BFA406297ABC55F2DA7E61BA49D562B21E500D5DE5701A7A2E139C40E589DE05CB9F327794F3A1DFE6E59E64C3919048ABD9363C7157C1A75ED27B7CAEA7C791306F61B65F44C59923FEC1EF9EACD853CA6E44553D8C946D6789329C52C7FEFDDEA74CD8D17638EAA0B49DFA6C141B600817068A9DB14AB769C3457C40735676BB3D4A92224646E780CCF4CB7FD2B9ED4AF453A323CBE1525236E4258F6C092EDA9CDE50AE0E85CF32FD5EC23023CB6D9BEE3CF7AA6369C23EC667EF3156A076A47035BCF182E33841FD43E5EC69CBBD48A538E67DD0E4A910974EC40239BA4093F1042E575325FAF00DE016E1E34571E27AC8DB8F212626D176611BE415FD9A29BF38D71A98C8123653699250BCD3C9CA9115AA8BF965222F0CA52CBE9A713E8E97D4D59F9B268C3E4A37FAACE9512E9071EA10761042C03AA5EA74CC9838CBE1F589270376FF45405D447F96D37CD63AE8B4C6980137D2C5BFD2D592345C; _iuqxldmzr_=32; P_INFO=m15136881343@163.com|1721199992|0|unireg|00&99|null&null&null#hen&410100#10#0#0|151343&1||15136881343@163.com; __csrf=2e3b2bccbdc68e08db922cc95700a24d; __csrf=2e3b2bccbdc68e08db922cc95700a24d; WM_NI=S0xxMA3cRhaGFGnTzDHxtdX9DMmUuj5%2FvVqBZ3%2BCnTsfQDDC0KtT5jFYRWZxmzMgQp7w2Iu1Iwty80J33Lhwfsn%2FkM%2BFT%2BRGPiOdhYi8qJb%2FawatqPZ%2B2LoetSi51l60TGc%3D; WM_NIKE=9ca17ae2e6ffcda170e2e6ee9bf25bb390978cdc3babef8ba2c14b929e9eaddb5fb8b4fab0d734b2908f8dd22af0fea7c3b92a91f0b899d04bf1bd9e89e44d8699a2b5f9508ca8bc85db338893a3b6f862f7f1bab7f44a9aede5a4ed60b1ba9fa5c749f495bcb5b86286879eb8d974afa68388d47cf5a9feaaf83b8ba9bc9abb3c8aedfdadeb7da6ada2d0ea47e99a9cccd14d94b78185eb53abe8bfabe125a3a9af95f45c9af5feadee6fb88da7d6b468f6f09ca8e237e2a3; JSESSIONID-WYYY=mKp%2FPtrVNt5eQ30YjEafE120Iw1rBRjmN%2Fkvl4RkhDsJM1mSUFyoe5bR%2B%2BA0ppFTuV%2F9iuVVJVhmkkeZFTRU1vOAilFGU1637MqEfxpMJjE3W278r4Zpm7M2P3%5CqP8HMvh2o02%5CKIhKa0mcGCulHeSvEHbB%5CsrwbyRtJ7ydcZQRb%2F1KP%3A1725107084994; playerid=54601304'
}


def get_id(id, headers):
    url = f'https://music.163.com/artist?id={id}'
    response = requests.get(url, headers=headers)
    pattern = r'<li><a href="/song\?id=(\d+)">([^<]+)</a></li>'
    matches = re.findall(pattern, response.text)
    ids = []
    names = []
    for match in matches:
        song_id, song_name = match
        ids.append(song_id)
        names.append(song_name)
    get_data(ids, names, headers)


def get_data(ids, names, headers):
    url = 'https://music.163.com/weapi/song/enhance/player/url/v1?csrf_token=2e3b2bccbdc68e08db922cc95700a24d'
    with open('./06_网易云音乐/main.js', 'r', encoding='utf-8') as f:
        js_code = f.read()
    ctx = execjs.compile(js_code)
    print("开始下载")
    print("-" * 20)
    for i in range(len(ids)):
        try:
            js = ctx.call('main', ids[i])
            params = js['encText']
            encSecKey = js['encSecKey']
            data = {
                'params': params,
                'encSecKey': encSecKey
            }
            response = requests.post(url, data=data, headers=headers)
            save(response.text, names[i])
        except:
            pass


def save(response_text, name):
    data = json.loads(response_text)
    url = data['data'][0]['url']
    result = requests.get(url).content
    with open(f'{dir}/{name}.m4a', 'wb') as f:
        f.write(result)
    print(f"《{name}》下载完毕！")
    print("-" * 20)


if __name__ == '__main__':
    singer_id = 3684
    dir = f'musicfiles/{singer_id}'
    if not os.path.exists(dir):
        os.makedirs(dir)
    # 传入歌手id
    get_id(singer_id, headers)
